package com.chijun.mform.process.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;

import com.chijun.mform.FormUtils;
import com.chijun.mform.R;
import com.chijun.mform.create.fragment.FormAddProcessFragment;
import com.chijun.mform.full.mode.ModeFormFullApprovePerson;
import com.chijun.mform.process.IHandlerLoadFormFull;
import com.chijun.mform.process.IWaitUploadCompleteListener;
import com.chijun.mform.process.ModeServerFullData;
import com.chijun.mform.process.view.ViewGetPingLunContentView;
import com.example.ccj.b.c.dialog.DialogBase;
import com.example.ccj.b.c.dialog.ErrorDialog;
import com.example.ccj.b.c.dialog.LoadingDialog;
import com.example.ccj.b.c.draw.TopBar;
import com.example.ccj.u.GenerateId;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.SPUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.TimeUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.tengxun.cos.CosDeleteCallBack;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


public class DialogPingLun2 extends DialogBase {

    ModeServerFullData serverFullData;
    IResultPingLunContentCallBack callBack;
    IHandlerLoadFormFull iHandlerLoadFormFull;

    public DialogPingLun2(Context context, ModeServerFullData serverFullData, IResultPingLunContentCallBack callBack, IHandlerLoadFormFull iHandlerLoadFormFull) {
        super(context);
        getContext();
        if (context instanceof Activity) {
            ToastUtils.showShort("是");

        } else {
            ToastUtils.showShort("否");
        }

        this.serverFullData = serverFullData;
        this.iHandlerLoadFormFull = iHandlerLoadFormFull;
        this.callBack = callBack;
    }
    ModeFormFullApprovePerson copyPerson = null;
    ModeFormFullApprovePerson pingLun = null;
    ViewGetPingLunContentView pl;

    @Override
    public void onInit() {
        isCanClose(false);
        setLayout(R.layout.dialog_view_ping_lun);
        setAlpha(1f);//透明度
        isCanClose(false);//点击允许关闭
        isShowBackground(false);//不显示背景
        setShowHeightRatio(true);//按比例显示
        setHeightRatio(0.5);//高度显示比例
        showInBottom();//底部弹出
        setFull(true);//是否铺满
        goneTitleLeftImage();


        initView();
    }

    public void initView() {

//        if (getContext() instanceof Activity) {
//            ToastUtils.showShort("是");
//
//        } else {
//            ToastUtils.showShort("否");
//        }

        TopBar topBar = findViewById(R.id.dialog_view_ping_lun_top_bar);
        topBar.setLeftClick(v -> dismiss());
        pl = findViewById(R.id.dialog_ping_lun_view);
        Button cancel = findViewById(R.id.btn_cancel);
        success = findViewById(R.id.btn_ok);


        pingLun = new ModeFormFullApprovePerson();
        //流程表单添加方法 当前状态时审批中并且当前的审批人不为空 放入当前审批人下
        if (serverFullData.launchedForm.state == 1 && serverFullData.thisFormFullApprovePerson != null) {
            //获取当前审批人，将该评论加在其下方
            copyPerson = serverFullData.thisFormFullApprovePerson;
            pingLun.processId = copyPerson.processId;
        } else {
            //数据表单添加方法 不存在当前审批人或者不为流程表单 或者审批结束了 放到最后
            if (!serverFullData.formApproveProcessList.isEmpty()) {
                pingLun.processId = serverFullData.formApproveProcessList.get(serverFullData.formApproveProcessList.size()-1).id;
            }
        }
        String prefix = "/"+serverFullData.launchedForm.formId + "/" +
                serverFullData.launchedForm.id + "/" + "pl" + "/" +
                SPUtils.getInstance().getString("user_id") + "-" +
                SPUtils.getInstance().getString("user_name") + "/";

        pl.sateData(serverFullData, prefix,pingLun);

        //取消后 检查是否有图片上传，有的话删除掉
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (callBack != null) callBack.onCancel();
                dismiss();
            }
        });

        success.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(pl.opinionStr) && StringUtils.isEmpty(pl.imgStr)) {
                    ToastUtils.showShort("你不能提交一个空的评论！");
                    return;
                } else {
                    success.setEnabled(false);
                    jjjjj();
                }

                if (pingLun != null) {
                    pingLun.id = GenerateId.getId();
                    pingLun.formFullId = serverFullData.launchedForm.id;
                    pingLun.note = "评论";
                    pingLun.state = FormAddProcessFragment.SHEN_PI_STATE_PING_LUN;
                    pingLun.startTime = TimeUtils.getNowString();
                    pingLun.endTime = TimeUtils.getNowString();
                    pingLun.image = pl.imgStr.toString();
                    pingLun.opinion = pl.opinionStr;
                    pingLun.personName = SPUtils.getInstance().getString("user_name");
                    pingLun.personId = SPUtils.getInstance().getString("user_id");

                    if (iHandlerLoadFormFull != null) {
                        LoadingDialog loadingDialog = new LoadingDialog(getContext());
                        loadingDialog.showLoading();
                        iHandlerLoadFormFull.uploadPingLun(pingLun, new IWaitUploadCompleteListener() {
                            @Override
                            public void onComplete() {
                                loadingDialog.dismiss();
                                //添加流程
                                if (callBack != null) {
                                    if (copyPerson != null) {
                                        callBack.onResult(copyPerson.id,pingLun);
                                    } else {
                                        callBack.onResult(1,pingLun);
                                    }
                                    ToastUtils.showShort("评论成功");
                                    dismiss();
                                } else {
                                    LogUtils.e("无回调无法返回评论数据！");
                                }

                            }
                            @Override
                            public void onError(String value) {
                                loadingDialog.dismiss();
                                ErrorDialog errorDialog = new ErrorDialog(v.getContext(),value);
                                errorDialog.show();
                            }
                        });
                    } else {
                        LogUtils.e("FormBuilder类中的iHandlerLoadFormFull接口未实例化，无法上传评论");
                    }
                }
            }
        });

    }

    public static final int releaseButton = 1111;
    Button success;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == releaseButton) {
                success.setEnabled(true);
            }
            return false;
        }
    });

    Disposable disposable;
    @SuppressLint("SetTextI18n")
    private void jjjjj(){
        // 从 4 开始倒数，共倒数 5 个数，延迟 2 秒开始倒数
        success.setText("等待5");
        success.setTextColor(Color.parseColor("#dddddd"));

        Observable<Integer> take = Observable.interval(1, TimeUnit.SECONDS).map(aLong -> 4 - aLong.intValue()).take(5);

        disposable = take.subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                if (integer == 0) {
                    success.setEnabled(true);
                    success.setTextColor(Color.parseColor("#2196F3"));
                    success.setText("提交评论");
                }
                else success.setText("等待" + integer);
            }
        });
    }

    @Override
    public void dismiss() {
        LogUtils.d("走dismiss删除：");
        if (pl != null) {
            if (StringUtils.isNoEmpty(pl.imgStr)) {
                String[] split = pl.imgStr.toString().split(",");
                for (String s : split) {
                    LogUtils.d("删除：" + s);
                    FormUtils.cosDeleteFile(pl.getContext(), s, new CosDeleteCallBack() {
                        @Override
                        public void onComplete(String s) {}
                        @Override
                        public void onError(String s) {}
                    });
                }
            }
        }
        if (disposable != null) disposable.dispose();
        super.dismiss();
    }


    public interface IResultPingLunContentCallBack {
        /**
         * 返回评论数据
         * @param id 插入在人员节点下的人员id
         * @param person 评论
         */
        void onResult(long id, ModeFormFullApprovePerson person);
        //取消选择
        void onCancel();
    }


}

